package com.hsav.kcxb.activity;

import android.app.FragmentManager;
import android.content.Intent;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.MediaController;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.Toast;
import android.widget.VideoView;

import com.hsav.kcxb.R;
import com.hsav.kcxb.adapter.PlayRemarkAdapter;
import com.hsav.kcxb.bean.PlayRemarkBean;
import com.hsav.kcxb.fragment.sing.CommentFragment;
import com.hsav.kcxb.fragment.sing.GiftFragment;
import com.hsav.kcxb.utils.MyUtil;
import com.kcbsdk.AFetchType;
import com.kcbsdk.EventHandler;
import com.kcbsdk.MyManage.AHeadPortrait;

import java.io.IOException;
import java.util.ArrayList;

import static com.hsav.kcxb.main.MSYS.mMyRankBa;

/**
 * Created by zhao on 2016/12/21.
 */

public class PlayActivity extends BaseActivity implements GiftFragment.OnFragmentInteractionListener, CommentFragment.OnFragmentInteractionListener {

    private MediaPlayer mMediaPlayer;
    private VideoView mVideoView;
    private ImageView mPlayImg;
    private int[] mResourceIds = {0};
    private ImageView mPlayPrevious;
    private ImageView mPlayNext;
    private STATUS mPlayStatus = STATUS.UNKNOWN;
    private int mPlayIndex = 0;
    private int mUserID;
    private int mSongID;
    private boolean mIsVideo;
    private boolean isPlaying;
    private String gsPlayFile = "";
    private final static String TAG = PlayActivity.class.getSimpleName();
    private ListView mRemarkListView;
    private LinearLayout remarkLayout;
    private ImageView mLikeImg;
    private ImageView mPlayModeImg;
    private MediaController mMediaController;
    private ViewGroup mFragmentContainer;
    private GiftFragment giftFragment;
    private CommentFragment commentFragment;

    public enum STATUS {
        UNKNOWN, PLAYING, PAUSE, SEEKING, END, ERROR
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.aty_play_main);
        Intent intent = getIntent();
        mUserID = intent.getIntExtra("userID", 0);
        mSongID = intent.getIntExtra("songID", 0);
        mIsVideo = intent.getBooleanExtra("isVideo", false);
//        mMyRankBa.Log("PlayActivity "+mUserID+" "+mSongID + " " + mIsVideo);

        initKcbData();
        mMyRankBa.fetchSongDetail(mUserID, mSongID);
        if (mIsVideo) {
            mMyRankBa.fetchSongFile(mUserID, mSongID, true);
//            mMyRankBa.fetchSongFile(mUserID, mSongID, false);
        }
        else {
            mMyRankBa.fetchSongFile(mUserID, mSongID, false);
        }

        initView();
        setPlayer(0);
        setHandler();
        initListView();
        initGiftView();
    }
    private void initKcbData(){
        mMyRankBa.setUiEventCallBack(this, new EventHandler()
        {
            @Override
            public void onComplete(int methodType, boolean isFail, String message){
                if (methodType > 0){
                    if (isFail){
                        mMyRankBa.Toast(String.format("%s%s(%08x)", getString(R.string.methodError), message, methodType));
                    }
                    else {
                        if (mMyRankBa.isSucessFetchUserDetail(methodType)){
                            mMyRankBa.fetchCommentListDbs(AFetchType.LIST_NORMAL, mUserID, mSongID);
                            String gsLocal_1 = "用户信息：";
                            gsLocal_1 += String.format(" NickName：%s", mMyRankBa.mAUserDetail.NickName);
                            gsLocal_1 += String.format(" SongQty：%d", mMyRankBa.mAUserDetail.SongQty);
                            gsLocal_1 += String.format(" FansQty：%d", mMyRankBa.mAUserDetail.FansQty);
                            gsLocal_1 += String.format(" ListenQty：%d", mMyRankBa.mAUserDetail.ListenQty);
                            gsLocal_1 += String.format(" Intro：%s", mMyRankBa.mAUserDetail.Intro);
                            gsLocal_1 += String.format(" jpg：%s", mMyRankBa.mAUserDetail.HeadFile);
                            mMyRankBa.Toast(gsLocal_1);
                        }
                        if (mMyRankBa.isSucessFetchSongDetail(methodType)){
//                            mMyRankBa.fetchUserInfo(mUserID, AHeadPortrait.IMG_LARGE);
                            String gsLocal_1 = "歌曲信息：";
                            gsLocal_1 += String.format(" SongName：%s", mMyRankBa.mASongDetail.SongName);
                            gsLocal_1 += String.format(" Comment：%d", mMyRankBa.mASongDetail.CommentQty);
                            gsLocal_1 += String.format(" 花：%d", mMyRankBa.mASongDetail.FlowerQty);
                            gsLocal_1 += String.format(" 转发：%d", mMyRankBa.mASongDetail.ShareQty);
                            gsLocal_1 += String.format(" Date：%d", mMyRankBa.mASongDetail.ReleaseDate);
                            if (mMyRankBa.mASongDetail.SongIntro.length() > 8) {
                                gsLocal_1 += String.format(" Intro：%s", mMyRankBa.mASongDetail.SongIntro.substring(0, 8));
                            }
                            if (mIsVideo) {
                                gsPlayFile = mMyRankBa.mASongDetail.VideoFile;
                                gsLocal_1 += String.format(" mp4：%s", mMyRankBa.mASongDetail.VideoFile);
                            }
                            else {
                                gsPlayFile = mMyRankBa.mASongDetail.AudioFile;
                                gsLocal_1 += String.format(" mp3：%s", mMyRankBa.mASongDetail.AudioFile);
                            }
                            mMyRankBa.Toast(gsLocal_1);
                        }
                        if (mMyRankBa.isSucessCommentListDbs(methodType)){
                            mMyRankBa.Log("评论数据："+mMyRankBa.g4CommentListMax);
                        }

                    }
                } else{
                    if (mMyRankBa.isEventDownloadAudio()){
                        mMyRankBa.Log("下载MP3："+mMyRankBa.g4DownAudioCounter+"/"+mMyRankBa.g4DownAudioLength);
                    }
                    if (mMyRankBa.isEventDownloadVideo()){
                        mMyRankBa.Log("下载MP4："+mMyRankBa.g4DownVideoCounter+"/"+mMyRankBa.g4DownVideoLength);
                        if (mMyRankBa.g4DownVideoCounter > 2000000 && !isPlaying){
                            isPlaying = true;
                            playStart();
                        }
                    }
                }
            }
        });

    }

    private void playStart(){
        if ("".equals(gsPlayFile)){
            mMyRankBa.Log("没有找到文件");
            return;
        }
        if (mIsVideo) {
            mMyRankBa.Log("开始播放MP4" + gsPlayFile);
            mVideoView.setVideoPath(gsPlayFile);
            mVideoView.start();
        }
        else {
            mMyRankBa.Log("开始播放MP3");
        }
    }

    private void initGiftView() {
        mFragmentContainer = (ViewGroup) findViewById(R.id.fragment_container);
        View layoutToGift = findViewById(R.id.layout_to_gift);
        View layoutToComment = findViewById(R.id.layout_to_comment);
        View layoutToShare = findViewById(R.id.layout_to_share);

        layoutToGift.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mFragmentContainer.setVisibility(View.VISIBLE);
                FragmentManager fragMgr = getFragmentManager();
                giftFragment = GiftFragment.newInstance("", "");
                fragMgr.beginTransaction().add(R.id.fragment_container, giftFragment, GiftFragment.class.getName()).commit();
            }
        });
        layoutToComment.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mFragmentContainer.setVisibility(View.VISIBLE);
                FragmentManager fragMgr = getFragmentManager();
                commentFragment = CommentFragment.newInstance("", "");
                fragMgr.beginTransaction().add(R.id.fragment_container, commentFragment, GiftFragment.class.getName()).commit();
            }
        });

        layoutToShare.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                MyUtil.shardMsg(PlayActivity.this,"标题","好听的歌，值得分享","");
            }
        });
    }

    @Override
    public void onBackPressed() {
        FragmentManager fragMgr = getFragmentManager();
        if (giftFragment != null)
        {
            fragMgr.beginTransaction().remove(giftFragment).commit();
            giftFragment = null;
            mFragmentContainer.setVisibility(View.GONE);
        }
        else if (commentFragment != null)
        {
            fragMgr.beginTransaction().remove(commentFragment).commit();
            commentFragment = null;
            mFragmentContainer.setVisibility(View.GONE);
        }
        else
            super.onBackPressed();
    }

    @Override
    public void onCloseButtonClicked() {
        FragmentManager fragMgr = getFragmentManager();
        if (giftFragment != null)
        {
            fragMgr.beginTransaction().remove(giftFragment).commit();
            giftFragment = null;
        }
        mFragmentContainer.setVisibility(View.GONE);
    }

    @Override
    public void onCommentCommitted() {
        FragmentManager fragMgr = getFragmentManager();
        if (commentFragment != null)
        {
            fragMgr.beginTransaction().remove(commentFragment).commit();
            commentFragment = null;
        }
        mFragmentContainer.setVisibility(View.GONE);
    }

    private void initListView() {
        mRemarkListView = (ListView)findViewById(R.id.lv_play_remark);
        remarkLayout = (LinearLayout)findViewById(R.id.ll_play_remark);

        ArrayList<PlayRemarkBean> playRemarkBeenList = new ArrayList<>();
        playRemarkBeenList.add(new PlayRemarkBean(0,"zhao","haha","122",""));
        playRemarkBeenList.add(new PlayRemarkBean(3,"zhang ","good","45435",""));
        playRemarkBeenList.add(new PlayRemarkBean(5,"wang","well","3534",""));
        playRemarkBeenList.add(new PlayRemarkBean(0,"zhao","haha","122",""));
        playRemarkBeenList.add(new PlayRemarkBean(3,"zhang ","good","45435",""));
        playRemarkBeenList.add(new PlayRemarkBean(5,"wang","well","3534",""));
        PlayRemarkAdapter playRemarkAdapter = new PlayRemarkAdapter(this, playRemarkBeenList);
        mRemarkListView.setAdapter(playRemarkAdapter);
        int totalHeight = MyUtil.setListViewHeightBasedOnChildren(mRemarkListView);
        ViewGroup.LayoutParams layoutParams = remarkLayout.getLayoutParams();

        RelativeLayout relativeLayout = (RelativeLayout)findViewById(R.id.rl_play_bottom);
        int bottomHeight = relativeLayout.getMeasuredHeight();
        layoutParams.height = totalHeight + 160;
        Log.i(TAG,"height="+bottomHeight);
        remarkLayout.setLayoutParams(layoutParams);
    }

    private void initView() {
        ScrollView scrollView = (ScrollView) findViewById(R.id.scrollView);
        mPlayImg = (ImageView) findViewById(R.id.iv_playing);
        mPlayPrevious = (ImageView) findViewById(R.id.iv_play_previous);
        mPlayNext = (ImageView) findViewById(R.id.iv_play_next);
        mPlayModeImg = (ImageView)findViewById(R.id.iv_play_mode);
        mPlayModeImg.setTag(R.drawable.play_loop);

        mPlayModeImg.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if((int)mPlayModeImg.getTag() == R.drawable.play_loop){
                    mPlayModeImg.setImageResource(R.drawable.play_order);
                    mPlayModeImg.setTag(R.drawable.play_order);
                }else{
                    mPlayModeImg.setImageResource(R.drawable.play_loop);
                    mPlayModeImg.setTag(R.drawable.play_loop);
                }
            }
        });

        mLikeImg = (ImageView)findViewById(R.id.iv_play_collect);
        mLikeImg.setTag(R.drawable.like_unselect);
        mLikeImg.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if((int)mLikeImg.getTag() == R.drawable.like_unselect){
                    mLikeImg.setImageResource(R.drawable.like_select);
                    mLikeImg.setTag(R.drawable.like_select);
                }else{
                    mLikeImg.setImageResource(R.drawable.like_unselect);
                    mLikeImg.setTag(R.drawable.like_unselect);
                }
            }
        });

        mPlayImg.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mPlayStatus == STATUS.PLAYING) {
                    mMediaPlayer.pause();
                    mPlayStatus = STATUS.PAUSE;
                    mPlayImg.setImageResource(R.drawable.play_pause);
                } else if (mPlayStatus == STATUS.PAUSE) {
                    mMediaPlayer.start();
                    mPlayStatus = STATUS.PLAYING;
                    mPlayImg.setImageResource(R.drawable.play_play);
                }
            }
        });
        mPlayPrevious.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                setPlayer(mPlayIndex - 1);
            }
        });

        mPlayNext.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                setPlayer(mPlayIndex + 1);
            }
        });

        mVideoView = (VideoView) findViewById(R.id.vv_info_head);
        mMediaController = (MediaController)findViewById(R.id.mc_media_controller);
        mMediaController = new MediaController(this);
        mMediaController.setAnchorView(mVideoView);
        mMediaController.setKeepScreenOn(true);
        mVideoView.setMediaController(mMediaController);
        if (mIsVideo) {
            mMyRankBa.fetchSongFile(mUserID, mSongID, true);
//            mMyRankBa.fetchSongFile(mUserID, mSongID, false);
            mVideoView.setVisibility(View.VISIBLE);
            findViewById(R.id.iv_play_container).setVisibility(View.GONE);
            mVideoView.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                @Override
                public void onCompletion(MediaPlayer mp) {
                    Log.d(TAG, "播放完成");
//                dispose();
                }
            });

        }
        else {
            mMyRankBa.fetchSongFile(mUserID, mSongID, false);
//        mMediaPlayer = MediaPlayer.create(this,R.raw.music);
            mVideoView.setVisibility(View.GONE);
            findViewById(R.id.iv_play_container).setVisibility(View.VISIBLE);
        }
        mMediaPlayer = new MediaPlayer();

        CheckBox checkAttention = (CheckBox) findViewById(R.id.radio_attention);
        checkAttention.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                Toast.makeText(PlayActivity.this, isChecked ? "已关注" : "已取消关注", Toast.LENGTH_SHORT).show();
            }
        });
    }

    private void setHandler() {
        mMediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mp) {
                setPlayer(mPlayIndex + 1);
            }
        });

        mMediaPlayer.setOnErrorListener(new MediaPlayer.OnErrorListener() {
            @Override
            public boolean onError(MediaPlayer mp, int what, int extra) {
                Log.i(TAG, "onError " + what + "," + extra);
                return false;
            }
        });
    }

    private void setPlayer(int pos) {
        if (pos < 0) {
            pos = mResourceIds.length + pos;
        }
        mPlayIndex = pos % mResourceIds.length;
        String musicUrl = "android.resource://" + getPackageName() + "/" + mResourceIds[mPlayIndex];
        Uri uri = Uri.parse(musicUrl);

        try {
            mMediaPlayer.reset();
            mMediaPlayer.setDataSource(this, uri);
            mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
            mMediaPlayer.prepareAsync();
            mMediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
                @Override
                public void onPrepared(MediaPlayer mp) {
                    mPlayStatus = STATUS.PLAYING;
                    mMediaPlayer.start();
                    mPlayImg.setImageResource(R.drawable.play_pause);
                }
            });
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onStop() {
        super.onStop();
        if (mMediaPlayer != null) {
            mMediaPlayer.stop();
            mMediaPlayer.release();
            mMediaPlayer = null;
        }
    }
    public String SHOW_FORMAT_DATE(long g4Local_1) {
        g4Local_1 = g4Local_1 / 1000;
        return String.format("%02d:%02d", g4Local_1 /60, g4Local_1%60);
    }
}
